package jdbc;

import java.sql.*;

/**
 * 数据库工具类
 *
 * @author Chova
 * @date 2022/05/31
 */
public class DBUtil {

    private static final String JdbcDriver = "com.mysql.jdbc.Driver";
    private static final String Url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimeZone=UTC";
    private static final String Username = "crrcdt";
    private static final String Password = "crrcdt@2022";

    private static Connection conn=null;

    // 静态代码块.用于数据库的加载,连接
    static {
        try {
            // 1. 加载JDBC驱动程序
            Class.forName(JdbcDriver);
            // 2. 获取数据库连接
            conn = DriverManager.getConnection(Url, Username, Password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        return conn;
    }

    public static void main(String[] args) {
        try {
            // 执行数据库操作
            Statement stmt = conn.createStatement();
            String sql = "select * from user";
            // 执行SQL语句
            ResultSet rs = stmt.executeQuery(sql);

            // 输出结果集
            while (rs.next()) {
                System.out.println(rs.getString("user_name") + "," + rs.getInt("user_no"));
            }

            // 关闭数据库连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
